﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Ovvio.Web.Areas.Admin.Models;
using Ovvio.Web.Core;
using Ovvio.Data;
using Ovvio.Web.Areas.Admin.ModelProviders;

namespace Ovvio.Web.Areas.Admin.Controllers
{
    public class CatalogueController : BaseController<int,CatalogueModel,Product,OvvioDataContext>
    {
        public CatalogueController() : base(new CatalogueModelProvider()) { }

        [HttpPost]
        public ActionResult Update(FormCollection model)
        {
            try
            {
                if (ModelState.IsValid)
                {
                    var original = _modelProvider.Get(Convert.ToInt32(model["Id"]));

                    original.IsOnStock = Convert.ToBoolean(model["IsOnStock"].Split(',').First());
                    original.IsPublished = Convert.ToBoolean(model["IsPublished"].Split(',').First());
                    original.SetRatingId(Convert.ToInt32(model["RatingId"]));
                    original.SetItemTypeId(Convert.ToInt32(model["ItemTypeId"]));
                    
                    if (_modelProvider.Save(original))
                        return RedirectToAction("Index");
                    else
                        ModelState.AddModelError("", "No changes where made.");
                }

            }
            catch (Exception ex)
            {
                ModelState.AddModelError("", ex.InnerException != null ? ex.InnerException.Message : ex.Message);
            }
            return RedirectToAction("Index");

        }

        public ActionResult Thumb(int id)
        {
            var image = ((CatalogueModelProvider)_modelProvider).GetThumbnail(id);

            if (image != null)
                return File(image, "image/jpg");

            return File(new byte[] { }, "image/jpg");
        }
    }
}
